// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    const { startDate } = event
    
    if (!startDate) {
      return {
        status: 'error',
        message: '参数错误：缺少开始日期'
      }
    }
    
    const start = new Date(startDate)
    const now = new Date()
    
    // 查找最近的周期记录，结束之前的周期
    const recentCycles = await db.collection('cycles')
      .where({
        user_id: userId,
        end_date: null // 未结束的周期
      })
      .get()
    
    // 如果有未结束的周期，先结束它
    if (recentCycles.data.length > 0) {
      const recentCycle = recentCycles.data[0]
      const recentStart = new Date(recentCycle.start_date)
      
      // 计算周期持续天数
      const duration = Math.floor((start - recentStart) / (24 * 60 * 60 * 1000))
      
      // 更新之前的周期
      await db.collection('cycles')
        .doc(recentCycle._id)
        .update({
          data: {
            end_date: start,
            duration: duration,
            updated_at: now
          }
        })
    }
    
    // 创建新周期
    const result = await db.collection('cycles')
      .add({
        data: {
          user_id: userId,
          start_date: start,
          end_date: null,
          duration: 0,
          is_predicted: false,
          created_at: now,
          updated_at: now
        }
      })
    
    return {
      status: 'success',
      data: {
        _id: result._id
      }
    }
  } catch (err) {
    return {
      status: 'error',
      message: err.message,
      error: err
    }
  }
} 